// @Author EthanScriptOn
// @Desc
package starter

import (
	"errors"
	"gitee.com/fatzeng/srf_switch_basic_components/util"
	"gitee.com/fatzeng/srf_switch_config/config_context"
	"gitee.com/fatzeng/srf_switch_config/config_define"
	"gitee.com/fatzeng/srf_switch_config/config_field_cache"
)

func ConfigOperateInitialization(ctx *config_context.ConfigInitializationContext) (err error) {
	defer util.HandleErr(&err)
	if ctx == nil {
		return errors.New("need an ConfigInitializationContext")
	}
	configs, err := configurationDetection(ctx)
	if err != nil {
		return err
	}
	if err = fieldCacheInitialization(ctx, configs); err != nil {
		return err
	}
	return Start(ctx)
}

func fieldCacheInitialization(ctx *config_context.ConfigInitializationContext, configs []interface{}) error {
	if expansionFieldCaches, err := config_field_cache.DisassemblyConfig(configs...); err != nil {
		return err
	} else {
		ctx.SetFieldCache(expansionFieldCaches)
		return nil
	}
}

func configurationDetection(ctx *config_context.ConfigInitializationContext) ([]interface{}, error) {
	configs, err := ctx.GetConfig()
	if err != nil {
		return nil, err
	}
	if len(configs) <= 0 {
		return nil, errors.New("missing required config parameter. Please provide a non-nil Config struct")
	}
	return configs, nil
}

func mergeConfigInitializationFieldCache(configInitializationContextFieldCache, initializationConfigFieldCache map[config_define.NodeElemType]*config_field_cache.FieldCache) (map[config_define.NodeElemType]*config_field_cache.FieldCache, error) {
	polymerizationMap, err := util.MergeMap(configInitializationContextFieldCache, initializationConfigFieldCache)
	if err != nil {
		return nil, err
	}
	finalRes, ok := polymerizationMap.(map[config_define.NodeElemType]*config_field_cache.FieldCache)
	if !ok {
		return nil, errors.New("merge polymerizationMap failed")
	}
	return finalRes, nil
}
